<template>
  <PageContainer title="客服中心">
    <div class="service-container">
      <!-- 客服筛选区域 -->
      <div class="filter-section">
        <el-select
          v-model="filterStatus"
          placeholder="全部状态"
          style="width: 160px; margin-right: 16px;"
        >
          <el-option
            v-for="status in statusOptions"
            :key="status.value"
            :label="status.label"
            :value="status.value"
          />
        </el-select>
        <el-input
          v-model="searchKeyword"
          placeholder="搜索客服昵称"
          clearable
          style="width: 200px;"
        />
      </div>

      <!-- 客服列表区域 -->
      <div class="contact-section">
        <h2 class="section-title">客服列表</h2>
        <el-row :gutter="20" v-if="filteredAdmins.length > 0">
          <el-col :span="8" v-for="admin in filteredAdmins" :key="admin._id">
            <div class="admin-card" @click="startChat(admin)">
              <!-- 客服头像 -->
              <div class="admin-avatar">
                <img :src="admin.avatar" alt="客服头像" />
              </div>
              <!-- 客服信息（调整为昵称+状态同行布局） -->
              <div class="admin-info">
                <h3 class="admin-nickname">{{ admin.nickname }}</h3>
                <span class="status-tag" :class="getStatusClass(admin.status)">
                  {{ formatStatus(admin.status) }} <!-- 新增：把英文转中文显示更友好 -->
                </span>
              </div>
            </div>
          </el-col>
        </el-row>
        <el-empty v-else-if="!loading" description="暂无客服数据" />
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-placeholder">
        <el-skeleton animation="wave" rows="5" />
      </div>
    </div>
  </PageContainer>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { getServiceList } from '@/api/service';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import PageContainer from '@/components/PageContainer.vue';
import defaultAvatar from '@/assets/service.jpg';

const router = useRouter();

const formatStatus = (status) => {
  const map = { online: '在线', busy: '忙碌', offline: '离线' };
  return map[status] || status;
};

// 状态过滤选项
const statusOptions = [
  { value: '', label: '全部状态' },
  { value: 'online', label: '在线' },
  { value: 'busy', label: '忙碌' },
  { value: 'offline', label: '离线' }
];

// 组件状态
const filterStatus = ref('');
const searchKeyword = ref('');
const loading = ref(true);
const admins = ref([]);

// 加载客服数据
const loadAdmins = async () => {
  try {
    const result = await getServiceList();
    // 1. 先拿后端返回的完整数据（请求库的响应体）
    const resData = result.data;

    // 2. 验证后端返回的 code（只有 0000 才是成功）
    if (resData.code !== '0000') {
      throw new Error(resData.msg || '获取客服列表失败');
    }

    // 3. 正确拿到客服列表（后端返回的 data 字段）
    const serviceList = resData.data || [];
    if (!Array.isArray(serviceList)) {
      throw new Error('接口返回数据格式异常');
    }

    admins.value = serviceList; // 赋值真正的列表数组
  } catch (error) {
    ElMessage.error(error.message || '加载客服数据失败');
    console.error('Error:', error);
    admins.value = [];
  } finally {
    loading.value = false;
  }
};

// 过滤逻辑也需容错
const filteredAdmins = computed(() => {
  if (!Array.isArray(admins.value)) return [];
  return admins.value
    .filter(admin =>
      admin.nickname.includes(searchKeyword.value) &&
      (filterStatus.value ? admin.status === filterStatus.value : true)
    )
    .sort((a, b) => a.nickname.localeCompare(b.nickname));
});

// 状态样式映射
const getStatusClass = (status) => {
  switch (status) {
    case 'online': return 'status-online';
    case 'busy': return 'status-busy';
    default: return 'status-offline';
  }
};

// 跳转到聊天页面
const startChat = (admin) => {
  router.push(`/article/session/${admin._id}`);
};

onMounted(() => {
  loadAdmins();
});
</script>

<style lang="scss" scoped>
.service-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
  height: 100%;
}

.filter-section {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}

.contact-section {
  flex: 1;
  overflow-y: auto;
}

.admin-card {
  cursor: pointer;
  display: flex;
  align-items: center;
  padding: 16px;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 12px rgba(0,0,0,0.08);
  transition: all 0.3s;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(0,0,0,0.1);
  }

  .admin-avatar {
    width: 56px; /* 稍微缩小头像，更协调 */
    height: 56px;
    border-radius: 50%;
    overflow: hidden;
    margin-right: 14px;
    
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  // 核心调整：让昵称和状态同行排列
  .admin-info {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between; // 昵称左、状态右
  }

  .admin-nickname {
    font-size: 14px;
    font-weight: 500;
    margin: 0; // 清除默认margin
  }

  // 状态标签优化：仅包裹文字，更紧凑
  .status-tag {
    display: inline-block; // 仅占文字宽度
    padding: 2px 6px; // 缩小内边距
    border-radius: 4px;
    font-size: 12px;
    line-height: 1.4; // 优化行高
  }

  .status-online {
    background-color: #67c23a;
    color: #fff;
  }

  .status-busy {
    background-color: #e6a23c;
    color: #fff;
  }

  .status-offline {
    background-color: #909399;
    color: #fff;
  }
}

.loading-placeholder {
  padding: 40px 0;
  text-align: center;
  color: #909399;
}
</style>